package com.changfen.util;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author changfeng.chen@things-matrix.com
 * @date 2022/8/27 11:00
 **/
public class BitUtils {
    private static final Log log = LogFactory.getLog(BitUtils.class);

    /**
     * 指定位置是否为1
     *
     * @param digit
     * @param position
     * @return
     * @throws Exception
     */
    public static boolean isOneInPosition(Long digit, Integer position) throws Exception {
        if (null == digit) {
            throw new Exception("BitUtils isOneInPosition digit is empty");
        }
        if (null == position) {
            throw new Exception("BitUtils isOneInPosition position is empty");
        }

        return (digit >> position - 1 & 1) == 1;
    }

    /**
     * 给指定位置设1
     * @param position
     * @return
     * @throws Exception
     */
    public static Long setOneInPosition(Integer... position) throws Exception {
        if (ArrayUtils.isEmpty(position)) {
            throw new Exception("BitUtils setOneInPosition position is empty");
        }
        Long result = 0L;
        for (Integer pos : position) {
            result = result | (1 << pos -1);
        }
        return result;
    }

    public static void main(String[] args) throws Exception {
        Long aLong = setOneInPosition(1, 2, 4);
        System.out.println(setOneInPosition(1,2,4));

        System.out.println(isOneInPosition(aLong,1));
        System.out.println(isOneInPosition(aLong,2));
        System.out.println(isOneInPosition(aLong,4));


    }

}
